#include "matrix.h"
#include <memory.h>

float * Matrix::identity_array_2x2;
float * Matrix::identity_array_3x3;
float * Matrix::identity_array_4x4;
Matrix * Matrix::class_matrix[3];
int Matrix::i;

// Returns identity matrix. El valor retornado es una nueva matriz con el resultado de la operacion
Matrix & Matrix::identity(int dimension)
{
	static Matrix & M = *class_matrix[dimension - 2];
	static float * arr;
	arr = dimension == 2? identity_array_2x2 : dimension == 3? identity_array_3x3 : identity_array_4x4;
	memcpy(M.m, arr, dimension * dimension);
	/*
	Esto es sin guardar los arrays de memoria locos que tengo estaticos
	static Matrix & M = *class_matrix[dimension - 2];
	memset(M.m, 0, M.values * sizeof(float));
	for (int i = 0, j = dimension+1; i<dimension; i++)
		M.m[i*j] = 1.0f;
	*/
	return M;
}

// Inicializar solo una vez o van a tener memory leacks 
void Matrix::initalize()
{
	for (int i = 0; i< 3; i++)
		class_matrix[i] = new Matrix(i+2);

	identity_array_2x2 = new float[4];
	identity_array_3x3 = new float[9];
	identity_array_4x4 = new float[16];

	memset(identity_array_2x2, 0, 4 * sizeof(float));
	for (int i = 0, j = 3; i<2; i++)
		identity_array_2x2[i*j] = 1.0f;

	memset(identity_array_3x3, 0, 9 * sizeof(float));
	for (int i = 0, j = 4; i<3; i++)
		identity_array_3x3[i*j] = 1.0f;

	memset(identity_array_4x4, 0, 16 * sizeof(float));
	for (int i = 0, j = 5; i<5; i++)
		identity_array_4x4[i*j] = 1.0f;
}

// Luego de llamar esta funcion no realizar operaciones sobre matrices
void Matrix::finalize()
{
	for (int i = 0; i< 3; i++)
		delete class_matrix[i];
	delete identity_array_4x4;
	delete identity_array_3x3;
	delete identity_array_2x2;
}
